package com.atguigu.msm.controller;

import com.atguigu.commonUtils.R;
import com.atguigu.msm.service.MsmService;
import com.atguigu.msm.utils.RandomUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/edumsm")
//@CrossOrigin
public class MsmController {

    @Autowired
    private MsmService msmService;

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    /**
     * 发送短信验证码
     *
     * @param phone
     * @return
     */
    @GetMapping("send/{phone}")
    public R sendMsm(@PathVariable String phone) {

        //1.从redis中获取验证码，能获取到直接返回
        String code = redisTemplate.opsForValue().get(phone);
        if (!StringUtils.isEmpty(code)) {
            return R.ok().data("code", code);
        }

        //从redis中获取不到，进行阿里云的发送
        //生成随机验证码，传递给阿里云发送
        code = RandomUtils.getFourBitRandom();
        System.out.println(code);

        Map<String, Object> param = new HashMap<>();
        param.put("code", code);

        //调用service的方法发送短信
        boolean result = msmService.send(param, phone);
        if (result) {
            //发送成功，把发送成功的验证码放到resid里面
            //设置有效时间
            redisTemplate.opsForValue().set(phone, code, 5, TimeUnit.MINUTES);

            return R.ok();
        } else {
            return R.error().message("短信发送失败");
        }

    }
}
